package com.magicborrow.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.volley.VolleyError;
import com.magicborrow.BaseLog;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.alipay.PayResult;
import com.magicborrow.beans.ApplyEntity;
import com.magicborrow.beans.StringBean;
import com.magicborrow.enums.PriceModeEnum;
import com.magicborrow.huanxin.ChatActivity;
import com.magicborrow.utils.ImageLoadUtil;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.view.ContactDialog;
import com.magicborrow.views.LoadingDialog;
import com.magicborrow.views.MsgDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ghost on 16/3/28.
 */
public class PayoutReceiveAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    private static final int TYPE_FOOT = 0;
    private static final int TYPE_NORMAL = 1;
    private ArrayList<ApplyEntity.ContentData> mData;
    private Activity mContext;
    private LayoutInflater mLayoutInflater;



    public PayoutReceiveAdapter(Activity pContext){
        this.mContext = pContext;
        mLayoutInflater = LayoutInflater.from(mContext);
    }

    public void setData(ArrayList<ApplyEntity.ContentData> pData){
        this.mData = pData;
    }

    public ArrayList<ApplyEntity.ContentData> getData(){
        return this.mData;
    }

    @Override
    public int getItemViewType(int position) {
        if(position+1 == getItemCount()){
            return TYPE_FOOT;
        }else{
            return TYPE_NORMAL;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(viewType == TYPE_FOOT){
            View view = mLayoutInflater.inflate(R.layout.load_more_footer,null);
            view.setTag("foot");
            return new FootViewHolder(view);
        }else if(viewType == TYPE_NORMAL){
            View view = mLayoutInflater.inflate(R.layout.payout_receive_item,null);
            return new PayoutReceiveItemViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if(holder instanceof PayoutReceiveItemViewHolder){
            final PayoutReceiveItemViewHolder hold = (PayoutReceiveItemViewHolder)holder;
            final ApplyEntity.ContentData bean = mData.get(position);
            BaseLog.e("ssss", Constants.ADDRESS+bean.getUser().getAvatar80());
            ImageLoadUtil.loadImage(hold.imv_head, Constants.ADDRESS+bean.getTarget().getAvatar80().split("\\?")[0],R.mipmap.head_default);
            String url = "";
            if(bean.getWare().getImages() != null && bean.getWare().getImages().size() > 0){
                url = Constants.ADDRESS+bean.getWare().getImages().get(0).getPreview();
            }
            ImageLoadUtil.loadImage(hold.good_pic,url,R.mipmap.img_default);
            hold.good_name.setText(bean.getWare().getName());
            hold.tv_name.setText(bean.getTarget().getNickname());
            //hold.tv_address.setText("地址: "+bean.getWare().getAddress());
            hold.borrowTime.setText("损坏描述: "+bean.getReason());
            String a = "赔偿金额: ￥"+bean.getClaimPrice();
            SpannableStringBuilder builder = new SpannableStringBuilder(a);
            ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
            builder.setSpan(redSpan, 5,a.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            hold.borrowShichang.setText(builder);
            float lendScaleAVG = bean.getUser().getLendScaleAVG();//借出者的信用评分
            hold.commentCountMsg.setText(lendScaleAVG+"分");
            hold.rb_pingfen.setRating(lendScaleAVG);
            String b = "实际支付押金: ￥"+ bean.getWareDeposit();
            builder = new SpannableStringBuilder(b);
            builder.setSpan(redSpan, 7,b.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            hold.tv_address.setText(builder);
            operateStatus(bean.getStatus(),hold.statusMsg,hold.leftStatus,hold.rightStatus,hold.statusLayout);
            hold.leftStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int status = bean.getStatus();
                    String lm = hold.leftStatus.getText().toString();
                    if((status == 0 || status == 1 || status == 4) && "确认赔付".equals(lm)){
                        if(bean.getClaimPrice()-bean.getWareDeposit()>0){
                            payClaim(bean,position);
                        }else {
                        sendRequest(bean,3,position,"您已确认赔付!");
                        }

                    }

                }
            });
            hold.rightStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int status = bean.getStatus();
                    String rm = hold.rightStatus.getText().toString();
                    if("联系物主".equals(rm)){
                       /* mContext.startActivity(new Intent(mContext, ChatActivity.class).putExtra("chatType", 1)
                                .putExtra("userId", bean.getTarget().getId() + "")
                                .putExtra("username", bean.getTarget().getNickname()).putExtra("avatarPath",
                                        bean.getTarget().getAvatar80()));*/
                        ContactDialog contactDialog = new ContactDialog(mContext
                                ,bean.getTarget().getNickname()
                                ,bean.getTarget().getId()
                                ,bean.getTarget().getMobile()
                                , bean.getTarget().getAvatar80());
                        contactDialog.show();
                    }

                }
            });
        }
    }
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(final Message msg) {

                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //  Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        mData.get(msg.what).setStatus(3);
                        PayoutReceiveAdapter.this.notifyItemChanged(msg.what);
                        MsgDialog dialog = new MsgDialog(mContext,"支付成功",null);
                        dialog.show();


                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            //  Toast.makeText(PayActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                            MsgDialog dialog = new MsgDialog(mContext,"支付结果确认中，请稍候",null);
                            dialog.show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            //    Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                            MsgDialog dialog = new MsgDialog(mContext,"支付失败，请稍候再试",null);
                            dialog.show();


                        }
                    }

        }

        ;
    };

    /**
     * 赔付订单支付
     * @param bean
     * @param position
     */
    private void payClaim(ApplyEntity.ContentData bean, final int position) {
        HashMap<String,String> params = new HashMap<>();
        params.put("acc_token", UserTools.getUser(mContext).getAcc_token());
        params.put("id",bean.getId()+"");
        final LoadingDialog dialog = new LoadingDialog(mContext);
        dialog.show();
        VolleyTool.get(Constants.URL_GET_CLAIM_PAYINFO, params, new VolleyTool.HTTPListener() {
            @Override
            public <T> void onResponse(T t, int requestCode) {
                dialog.dismiss();
                int code = -1;
                String message = "";
                try {
                    JSONObject json = new JSONObject(t.toString());
                    code = json.getInt("code");
                    message = json.getString("message");
                    final String data = json.getString("data");
                    if(code>=0){
                        Runnable payRunnable = new Runnable() {

                            @Override
                            public void run() {
                                // 构造PayTask 对象
                                PayTask alipay = new PayTask(mContext);
                                // 调用支付接口，获取支付结果
                                String result = alipay.pay(data, true);

                                Message msg = new Message();
                                msg.what = position;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };

                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    }else {
                        MsgDialog msgDialog = new MsgDialog(mContext,message,null);
                        msgDialog.show();
                    }
                } catch (JSONException e) {
                    //e.printStackTrace();
                }
            }

            @Override
            public void onErrorResponse(VolleyError error, int requestCode) {
                dialog.dismiss();

            }
        },0, null);
    }

    private ProgressDialog progressDialog = null;
    private void sendRequest(final ApplyEntity.ContentData bean, final int cStatus, final int position, final String msg){
        progressDialog = new ProgressDialog(mContext);
        progressDialog.show();
        Map<String,String> params = new HashMap<>();
        params.put("id",bean.getId()+"");
        params.put("status",cStatus+"");
        params.put("acc_token", UserTools.getUser(mContext).getAcc_token());
        VolleyTool.get(Constants.FLOW_CONTROL, params, new VolleyTool.HTTPListener() {
            @Override
            public <T> void onResponse(T t, int requestCode) {
                progressDialog.dismiss();
                try {
                    JSONObject json = new JSONObject(t.toString());
                    int code = json.getInt("code");
                    if(code == 0){
                        new MsgDialog(mContext,msg,null).show();
                        mData.get(position).setStatus(cStatus);
                        PayoutReceiveAdapter.this.notifyItemChanged(position);
                    }
                } catch (JSONException e) {
                    // e.printStackTrace();
                }
            }
            @Override
            public void onErrorResponse(VolleyError error, int requestCode) {
                progressDialog.dismiss();
                Toast.makeText(mContext,"服务器暂时无法链接",Toast.LENGTH_SHORT).show();
            }
        },0,null);
    }

    private void operateStatus(int status,TextView statusMsg,TextView leftStatus,TextView rightStatus,RelativeLayout statusLayout){
        String sStatusMsg = "";
        String sLeftStatus = "";
        String sRightStatus = "";
        switch (status){
            case 0:
            case 4:
                sStatusMsg = "物主请求赔付";
                sLeftStatus = "确认赔付";//3
                sRightStatus = "联系物主";	// 1
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 1:
                sStatusMsg = "物主已向平台申诉";
                sLeftStatus = "确认赔付";//3
                sRightStatus = "联系物主"; //
                statusLayout.setVisibility(View.VISIBLE);
                break;
            case 2://取消索赔
                sStatusMsg = " ";
                sLeftStatus = " "; 	// 无操作
                sRightStatus = " ";// 无操作
                statusLayout.setVisibility(View.GONE);
                break;
        }
        statusMsg.setText(sStatusMsg);
        leftStatus.setText(sLeftStatus);
        rightStatus.setText(sRightStatus);
    }

    @Override
    public int getItemCount() {
        return mData.size()+1;
    }



    public class PayoutReceiveItemViewHolder extends RecyclerView.ViewHolder {
        private ImageView imv_head;
        private TextView tv_name;
        private TextView statusMsg;
        private RatingBar rb_pingfen;
        private TextView commentCountMsg;
        private ImageView good_pic;
        private TextView good_name;
        private TextView borrowTime;
        private TextView borrowShichang;
        private TextView tv_address;
        private TextView shouldPay;
        private TextView leftStatus;
        private TextView rightStatus;
        private RelativeLayout statusLayout;


        public PayoutReceiveItemViewHolder(View view) {
            super(view);
            imv_head = (ImageView)view.findViewById(R.id.imv_head);
            tv_name = (TextView)view.findViewById(R.id.tv_name);
            statusMsg = (TextView)view.findViewById(R.id.statusMsg);
            rb_pingfen = (RatingBar)view.findViewById(R.id.rb_pingfen);
            commentCountMsg = (TextView)view.findViewById(R.id.commentCountMsg);
            good_pic = (ImageView)view.findViewById(R.id.good_pic);
            good_name = (TextView)view.findViewById(R.id.good_name);
            borrowTime = (TextView)view.findViewById(R.id.borrowTime);
            borrowShichang = (TextView)view.findViewById(R.id.borrowShichang);
            tv_address = (TextView)view.findViewById(R.id.tv_address);
            shouldPay = (TextView)view.findViewById(R.id.shouldPay);
            leftStatus = (TextView)view.findViewById(R.id.leftStatus);
            rightStatus = (TextView)view.findViewById(R.id.rightStatus);
            statusLayout = (RelativeLayout)view.findViewById(R.id.statusLayout);
        }
    }

    public class FootViewHolder extends RecyclerView.ViewHolder{

        public FootViewHolder(View itemView) {
            super(itemView);
        }

    }

}
